package org.framework.lazy.cloud.network.heartbeat.common.adapter;

import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.HandleChannelTypeAdvanced;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyChannelContext;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyCurrentChannelContext;
import org.springframework.core.Ordered;

import java.util.Comparator;
import java.util.List;

/**
 * 通道类型适配器
 */
@Slf4j
public class ChannelTypeAdapter {
    protected final List<HandleChannelTypeAdvanced> handleChannelTypeAdvancedList;

    public ChannelTypeAdapter(List<HandleChannelTypeAdvanced> handleChannelTypeAdvancedList) {
        this.handleChannelTypeAdvancedList = handleChannelTypeAdvancedList;
    }

    /**
     * 处理当前数据
     *
     * @param channelHandlerContext 当前通道上下文
     * @param msg                   通道数据
     */
    public void handler(ChannelHandlerContext channelHandlerContext, Object msg) {
        // 升序 处理器
        List<HandleChannelTypeAdvanced> handleChannelTypeAdvancedSortedList =
                handleChannelTypeAdvancedList
                        .stream()
                        .sorted(Comparator.comparing(Ordered::getOrder))
                        .toList();

        for (HandleChannelTypeAdvanced handleChannelTypeAdvanced : handleChannelTypeAdvancedSortedList) {
            if (handleChannelTypeAdvanced.support(msg)) {
                NettyCurrentChannelContext nettyCurrentChannelContext = new NettyCurrentChannelContext();
                nettyCurrentChannelContext.setChannelHandlerContext(channelHandlerContext);

//                log.info("处理器:{},客户端:{}, 处理类型:{}",handleChannelTypeAdvanced.getClass(),new String(msg.getClientId()),msg.getMysqlType());
                handleChannelTypeAdvanced.handler(nettyCurrentChannelContext, msg);
                return;
            }
        }
    }

    /**
     * 适配不同类型
     *
     * @param nettyChannelContext 上下文
     * @param msg                 信息
     */
    public void handler(NettyChannelContext nettyChannelContext, Object msg) {
        // 升序 处理器
        List<HandleChannelTypeAdvanced> handleChannelTypeAdvancedSortedList =
                handleChannelTypeAdvancedList
                        .stream()
                        .sorted(Comparator.comparing(Ordered::getOrder))
                        .toList();

        for (HandleChannelTypeAdvanced handleChannelTypeAdvanced : handleChannelTypeAdvancedSortedList) {
            if (handleChannelTypeAdvanced.support(msg)) {
//                log.info("处理器:{},客户端:{}, 处理类型:{}",handleChannelTypeAdvanced.getClass(),new String(msg.getClientId()),msg.getMysqlType());
                handleChannelTypeAdvanced.handler(nettyChannelContext, msg);
                return;
            }
        }
    }


}
